package com.w3coffee.web.oauth.sinaweibo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.w3coffee.web.User;
import com.w3coffee.web.control.CheckinToken;
import com.w3coffee.web.oauth.sinaweibo.sina.http.AccessToken;
import com.w3coffee.web.oauth.sinaweibo.sina.http.RequestToken;

import com.w3coffee.web.oauth.IOauthApi;
import com.w3coffee.web.oauth.sinaweibo.sina.Weibo;


public class SinaWeiboOauthApiImpl implements IOauthApi {
	private SinaWeiboConfig config = null;
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public SinaWeiboOauthApiImpl() {
	}
	
	/**
	 * 初始化。由Spring在装配好这个Bean以后调用，把新浪围脖的appKey和appSecret传到Weibo对象。
	 * 在Spring对这个Bean的配置XML中，必须加上init-method="initialize"。
	 */
	public void initialize() {
		
	}

	public SinaWeiboConfig getConfig() {
		return config;
	}

	public void setConfig(SinaWeiboConfig config) {
		this.config = config;
	}
	
	@Override
	public void oauthRequest(HttpServletRequest req, HttpServletResponse resp, String backUrl) throws Exception {
		Weibo weibo = new Weibo(config.getAppKey(), config.getAppSecret());
		RequestToken requestToken = weibo.getOAuthRequestToken(backUrl);
		CheckinToken ct = (CheckinToken) req.getSession(false).getAttribute("TOKEN");
		User user = ct.getUser();
		user.setAuthAgent(weibo);
		user.setRequestToken(requestToken);
		
		String authUrl = requestToken.getAuthenticationURL();
		resp.sendRedirect(authUrl);
	}

	@Override
	public void doAuth(User user) throws Exception {
		RequestToken requestToken = (RequestToken) user.getRequestToken();
		AccessToken accessToken = requestToken.getAccessToken(user.getVerifier());
		user.setAccessToken(accessToken);

		Weibo weibo = (Weibo) user.getAuthAgent();
		com.w3coffee.web.oauth.sinaweibo.sina.User sinaUser = weibo.verifyCredentials();
		weibo.setToken(accessToken.getToken(), accessToken.getTokenSecret());
		
		user.setId(new Integer(sinaUser.getId()).toString());
		user.setName(sinaUser.getName());
		user.setHeadUrl(sinaUser.getProfileImageURL().toString());
		user.setFansNum(sinaUser.getFollowersCount());
		user.setIntro(sinaUser.getDescription());
		user.setVip(sinaUser.isVerified());
	}
}
